package com.thor.palmmall.rest.unifyversion.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.thor.commons.exception.ThorServiceException;
import com.thor.commons.util.Assert;
import com.thor.palmmall.dao.unifyversion.UIpapkDao;
import com.thor.palmmall.rest.unifyversion.AppInfo;
import com.thor.palmmall.rest.unifyversion.AppResponse;
import com.thor.palmmall.rest.unifyversion.AppResponseData;
import com.thor.palmmall.rest.unifyversion.UIpapk;
import com.thor.palmmall.rest.unifyversion.UIpapkType;
import com.thor.palmmall.rest.unifyversion.UnifyVersionService;

public class UnifyVersionServiceImpl implements UnifyVersionService {

  @Autowired
  @Qualifier("restTemplate")
  private RestTemplate template;

  @Override
  public UIpapk getVersionInfo(UIpapkType type, String authCode, String version)
      throws ThorServiceException {
    Assert.assertArgumentNotNull(type, "type");
    Assert.assertArgumentNotNull(authCode, "authCode");
    Assert.assertArgumentNotNull(version, "version");

    UIpapk uipapk = uipapkDao.getVersionInfo(type, authCode, version);
    if (uipapk != null) {
      String sVersion = uipapk.getVersion();
      String sApiKey = uipapk.getApiKey();
      String sAppKey = uipapk.getAppKey();
      Boolean sNeedUpdate = uipapk.isNeedUpdate();
      if (sNeedUpdate) {
        // 默认为不需要更新
        uipapk.setNeedUpdate(false);
      }

      if (StringUtils.isNotBlank(sVersion) && !StringUtils.equals(sVersion, version)) {
        // 两个版本不相等，需要更新。去访问接口并拼接url
        try {
          HttpHeaders headers = new HttpHeaders();
          headers.add("Content-Type", "application/x-www-form-urlencoded");
          MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
          postParameters.add("_api_key", sApiKey);
          postParameters.add("appKey", sAppKey);
          HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
              postParameters, headers);
          AppResponse appResponse = template.postForObject("https://www.pgyer.com/apiv2/app/builds",
              requestEntity, AppResponse.class);
          if (appResponse != null) {
            Integer code = appResponse.getCode();
            if (code.equals(0)) {
              // 返回成功
              AppResponseData appResponseData = appResponse.getData();
              if (appResponseData != null) {
                List<AppInfo> appList = appResponseData.getList();
                for (AppInfo app : appList) {
                  if (app.getBuildVersion().equals(sVersion)) {
                    String url = "";
                    switch (type) {
                    case ipa:
                      url = "itms-services://?action=download-manifest&url=https://www.pgyer.com/app/plist/"
                          + app.getBuildKey();
                      break;
                    case apk:
                      url = "https://www.pgyer.com/apiv2/app/install?_api_key=" + sApiKey
                          + "&buildKey=" + app.getBuildKey();
                      break;
                    default:
                      break;
                    }

                    //返回数据库维护的新版本号
                    uipapk.setVersion(uipapk.getVersion());
                    uipapk.setUrl(url);
                    uipapk.setNeedUpdate(true);
                  }
                }
              }
            }
          }
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          return null;
        }
      }
    }else
      throw new ThorServiceException("企业识别码不正确");
    return uipapk;
  }

  @Autowired
  private UIpapkDao uipapkDao;
}
